<template>
  <div class="admin-logs">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3">操作日志</span>
      </template>
    </el-page-header>

    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover">
          <el-statistic title="总日志数" :value="statistics.total || 0">
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover">
          <el-statistic title="最近7天" :value="statistics.recent || 0">
            <template #prefix>
              <el-icon><Clock /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选栏 -->
    <el-card style="margin-top: 20px;">
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="搜索">
          <el-input
            v-model="filters.search"
            placeholder="管理员、目标名称、描述"
            clearable
            style="width: 250px;"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="filters.action" placeholder="全部" clearable style="width: 150px;">
            <el-option label="创建" value="create" />
            <el-option label="更新" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="导出" value="export" />
            <el-option label="导入" value="import" />
            <el-option label="切换状态" value="toggle" />
            <el-option label="审核" value="approve" />
            <el-option label="拒绝" value="reject" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标类型">
          <el-select v-model="filters.target_type" placeholder="全部" clearable style="width: 150px;">
            <el-option label="景点" value="景点" />
            <el-option label="用户" value="用户" />
            <el-option label="动态" value="动态" />
            <el-option label="评论" value="评论" />
            <el-option label="路线" value="路线" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 日志列表 -->
    <el-card style="margin-top: 20px;">
      <el-table
        v-loading="loading"
        :data="logs"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="admin_username" label="管理员" width="120" />
        <el-table-column prop="action_display" label="操作类型" width="100" />
        <el-table-column prop="target_type" label="目标类型" width="100" />
        <el-table-column prop="target_name" label="目标名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ip_address" label="IP地址" width="130" />
        <el-table-column prop="created_at" label="操作时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: center;"
      />
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Document, Clock, Search, Refresh } from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import logger from '../utils/logger'

export default {
  name: 'AdminLogs',
  components: {
    Document,
    Clock
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const loading = ref(false)
    const logs = ref([])
    const statistics = ref({})
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(20)
    
    const filters = ref({
      search: '',
      action: '',
      target_type: ''
    })

    const isAdmin = computed(() => store.getters.isAdmin)

    const fetchLogs = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          page_size: pageSize.value
        }
        
        if (filters.value.search) {
          params.search = filters.value.search
        }
        if (filters.value.action) {
          params.action = filters.value.action
        }
        if (filters.value.target_type) {
          params.target_type = filters.value.target_type
        }

        const response = await TravelAPI.getAdminLogs(params)
        logs.value = response.results || []
        total.value = response.count || 0
      } catch (error) {
        logger.error('获取操作日志失败:', error)
        ElMessage.error('获取操作日志失败')
      } finally {
        loading.value = false
      }
    }

    const fetchStatistics = async () => {
      try {
        const response = await TravelAPI.getLogStatistics()
        statistics.value = response || {}
      } catch (error) {
        logger.error('获取统计信息失败:', error)
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      fetchLogs()
    }

    const handleReset = () => {
      filters.value = {
        search: '',
        action: '',
        target_type: ''
      }
      currentPage.value = 1
      fetchLogs()
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchLogs()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchLogs()
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }

    const goBack = () => {
      router.push('/admin')
    }

    onMounted(() => {
      if (!isAdmin.value) {
        ElMessage.error('您没有管理员权限')
        router.push('/')
        return
      }
      fetchStatistics()
      fetchLogs()
    })

    return {
      loading,
      logs,
      statistics,
      total,
      currentPage,
      pageSize,
      filters,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      formatDateTime,
      goBack,
      Search,
      Refresh
    }
  }
}
</script>

<style scoped>
.admin-logs {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
}

.filter-form {
  margin-bottom: 0;
}

:deep(.el-card) {
  border-radius: 12px;
  border: none;
}

:deep(.el-statistic) {
  text-align: center;
}
</style>

